<?php

namespace app\services;

use plugin\admin\app\model\TeamSpeedUpConfig;
use plugin\admin\app\model\TeamSpeedUpLog;

class TeamReleaseLogService
{
    public static function getTeamReleaseLog($userId, $config)
    {
        $days = ConfigService::get('team_speed_up_days');

        if (TeamSpeedUpLog::where('user_id', $userId)->where('team_consume_limit', $config['sale_amount'])->count() == 0) {
            TeamSpeedUpLog::insert([
                'user_id' => $userId,
                'team_consume_limit' => $config['sale_amount'],
                'recommend_count' => 0,
                'config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                'should_release_days' => $days,
                'release_days' => 0,
                'created_time' => date('Y-m-d H:i:s')
            ]);
        }
    }

    public static function check($userId, $teamConsume)
    {
        $config = TeamSpeedUpConfig::where('sale_amount', '<=', $teamConsume)->orderByDesc('sale_amount')->first();

        if ($config) {
            self::getTeamReleaseLog($userId, $config);
        }
    }

    public static function incrementRecommendCount($parentId, $userId)
    {
        $log = TeamSpeedUpLog::where('user_id', $parentId)->orderByDesc('team_consume_limit')->first();

        if ($log) {
            $log->recommend_count++;
            $inviteUserIds = explode(',', $log['invite_user_ids']);
            $inviteUserIds[] = $userId;
            $log->invite_user_ids = join(',', $inviteUserIds);
            $log->save();
        }
    }

    public static function incrementDays($id)
    {
        $log = TeamSpeedUpLog::where('id', $id)->first();
        $log['release_days'] += 1;

        if ($log['release_days'] == $log['should_release_days']) {
            $log['status'] = TeamSpeedUpLog::STATUS_RELEASED;
        }

        $log->save();
    }

    public static function incrementReleaseAmount($id, $releaseAmount = 0)
    {
        $log = TeamSpeedUpLog::where('id', $id)->first();
        $log['release_amount'] = bcadd($log['release_amount'], $releaseAmount, 2);

        $log->save();
    }

    public static function list($userId)
    {
        return TeamSpeedUpLog::where('user_id', $userId)->where('status', TeamSpeedUpLog::STATUS_UN_RELEASE)->get()->toArray();
    }
}